<template>
  <div class="app-container" id="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker filterable clearable
          v-model="queryParams.startTime"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm"
          placeholder="请选择开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker filterable clearable
          v-model="queryParams.endTime"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm"
          placeholder="请选择结束时间">
        </el-date-picker>
      </el-form-item>
<!--      <el-form-item label="加班时长" prop="duration">-->
<!--        <el-input-->
<!--          v-model="queryParams.duration"-->
<!--          placeholder="请输入加班时长"-->
<!--          filterable clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="抄送人ID列表，英文逗号分隔" prop="ccIds">-->
<!--        <el-input-->
<!--          v-model="queryParams.ccIds"-->
<!--          placeholder="请输入抄送人ID列表，英文逗号分隔"-->
<!--          filterable clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="状态：待审批/已通过/已拒绝/已取消" prop="status">-->
<!--        <el-select v-model="queryParams.status" placeholder="请选择状态：待审批/已通过/已拒绝/已取消" filterable clearable>-->
<!--          <el-option-->
<!--            v-for="dict in dict.type.oa_overtime_apply_status"-->
<!--            :key="dict.value"-->
<!--            :label="dict.label"-->
<!--            :value="dict.value"-->
<!--          />-->
<!--        </el-select>-->
<!--      </el-form-item>-->
      <el-form-item label="申请时间" prop="applyTime">
        <el-date-picker filterable clearable
                        v-model="queryParams.applyTime"
                        type="datetime"
                        value-format="yyyy-MM-dd HH:mm"
                        placeholder="请选择申请时间">
        </el-date-picker>
      </el-form-item>
<!--      <el-form-item label="申请时间">-->
<!--        <el-date-picker-->
<!--          v-model="daterangeApplyTime"-->
<!--          style="width: 240px"-->
<!--          value-format="yyyy-MM-dd"-->
<!--          type="datetimerange"-->
<!--          range-separator="-"-->
<!--          start-placeholder="开始日期"-->
<!--          end-placeholder="结束日期"-->
<!--        ></el-date-picker>-->
<!--      </el-form-item>-->
<!--      <el-form-item label="创建时间" prop="createdTime">-->
<!--        <el-date-picker filterable clearable-->
<!--          v-model="queryParams.createdTime"-->
<!--          type="datetime"-->
<!--          value-format="yyyy-MM-dd"-->
<!--          placeholder="请选择创建时间">-->
<!--        </el-date-picker>-->
<!--      </el-form-item>-->
<!--      <el-form-item label="更新时间" prop="updatedTime">-->
<!--        <el-date-picker filterable clearable-->
<!--          v-model="queryParams.updatedTime"-->
<!--          type="datetime"-->
<!--          value-format="yyyy-MM-dd"-->
<!--          placeholder="请选择更新时间">-->
<!--        </el-date-picker>-->
<!--      </el-form-item>-->
<!--      <el-form-item label="申请人ID" prop="userId">-->
<!--        <el-input-->
<!--          v-model="queryParams.userId"-->
<!--          placeholder="请输入申请人ID"-->
<!--          filterable clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="申请人部门ID" prop="deptId">-->
<!--        <el-input-->
<!--          v-model="queryParams.deptId"-->
<!--          placeholder="请输入申请人部门ID"-->
<!--          filterable clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <!-- 更多查询条件-->
      <template v-if="isShowMore">


      </template>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button :icon="isShowMore?'el-icon-d-arrow-right':'el-icon-d-arrow-left'" size="mini" type="warning" @click="isShowMore = !isShowMore">更多查询</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['oa:overtime_apply:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['oa:overtime_apply:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['oa:overtime_apply:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['oa:overtime_apply:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-alert
      v-if="!isAdmin"
      title="仅显示您作为审批人或抄送人的加班申请"
      type="info"
      show-icon
      :closable="false"
      style="margin-bottom: 10px;"
    />

    <div class="apply-container">
      <!-- 普通用户：标签页 -->
      <template v-if="!isAdmin">
        <el-tabs v-model="activeTab" @tab-click="handleTabClick">
          <!-- 我的加班 -->
          <el-tab-pane label="加班记录" name="myApply">
            <el-table v-loading="loading" :data="myApplyList" stripe :height="tableHeight">
              <el-table-column type="index" width="55" label="序号" align="center" />
              <el-table-column label="开始时间" align="center" width="180">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d} {h}:{i}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="结束时间" align="center" width="180">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d} {h}:{i}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="加班时长" align="center" prop="duration" />
              <el-table-column label="加班事由" align="center" prop="reason" width="200"/>
              <el-table-column label="状态" align="center" prop="status">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.oa_overtime_apply_status" :value="scope.row.status"/>
                </template>
              </el-table-column>
              <el-table-column label="申请时间" align="center" width="180">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.applyTime, '{y}-{m}-{d} {h}:{i}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="180" fixed="right">
                <template #default="scope">
                  <el-button
                    v-if="scope.row.status === 'pending'"
                    size="mini"
                    type="text"
                    icon="el-icon-s-promotion"
                    @click="handleSubmit(scope.row)"
                    v-hasPermi="['oa:overtime:submit']"
                  >
                    发送
                  </el-button>
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-info"
                    @click="handleInfo(scope.row)"
                    v-hasPermi="['oa:overtime:query']"
                  >详情</el-button>
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-edit"
                    @click="handleUpdate(scope.row)"
                    v-hasPermi="['oa:overtime:edit']"
                  >修改</el-button>
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click="handleDelete(scope.row)"
                    v-hasPermi="['oa:overtime:remove']"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>

          <!-- 审批记录 -->
          <el-tab-pane label="审批记录" name="approval">
            <el-table v-loading="loading" :data="approvalList" stripe :height="tableHeight">
              <el-table-column type="index" width="55" label="序号" align="center" />
              <el-table-column label="加班事由" align="center" prop="reason" />
              <el-table-column label="开始时间" align="center" width="180">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d} {h}:{i}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="结束时间" align="center" width="180">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d} {h}:{i}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="加班时长" align="center" prop="duration" />
              <el-table-column label="状态" align="center" prop="status">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.oa_overtime_apply_status" :value="scope.row.status"/>
                </template>
              </el-table-column>
              <el-table-column label="申请时间" align="center" width="180">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.applyTime, '{y}-{m}-{d} {h}:{i}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="150" fixed="right">
                <template #default="scope">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-info"
                    @click="handleApprovalDetail(scope.row)"
                    v-hasPermi="['oa:overtime:approve']"
                  >处理</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>

          <!-- 抄送记录 -->
          <el-tab-pane label="抄送记录" name="copied">
            <el-table v-loading="loading" :data="copiedList" stripe :height="tableHeight">
              <el-table-column type="index" width="55" label="序号" align="center" />
              <el-table-column label="加班事由" align="center" prop="reason" />
              <el-table-column label="开始时间" align="center" width="180">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d} {h}:{i}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="结束时间" align="center" width="180">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d} {h}:{i}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="加班时长" align="center" prop="duration" />
              <el-table-column label="状态" align="center" prop="status">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.oa_overtime_apply_status" :value="scope.row.status"/>
                </template>
              </el-table-column>
              <el-table-column label="申请时间" align="center" width="180">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.applyTime, '{y}-{m}-{d} {h}:{i}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="120" fixed="right">
                <template #default="scope">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-info"
                    @click="handleInfo(scope.row)"
                  >查看</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </template>

      <!-- 管理员视图 -->
      <template v-else>
    <el-table v-loading="loading" :data="overtime_applyList" @selection-change="handleSelectionChange" stripe :height="tableHeight">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" width="55" label="序号" align="center" fixed/>
<!--      <el-table-column label="主键ID" align="center" prop="id" />-->
      <el-table-column label="加班事由" align="center" prop="reason" />
      <el-table-column label="开始时间" align="center" prop="startTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="加班时长" align="center" prop="duration" />
<!--      <el-table-column label="审批人ID" align="center" prop="approverIds" />-->
      <el-table-column label="审批人姓名" align="center" prop="approverNames" />
<!--      <el-table-column label="抄送人ID" align="center" prop="ccIds" />-->
      <el-table-column label="抄送人姓名" align="center" prop="ccNames" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.oa_overtime_apply_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="申请时间" align="center" prop="applyTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.applyTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
<!--      <el-table-column label="创建时间" align="center" prop="createdTime" width="180">-->
<!--        <template slot-scope="scope">-->
<!--          <span>{{ parseTime(scope.row.createdTime, '{y}-{m}-{d} {h}:{i}') }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="更新时间" align="center" prop="updatedTime" width="180">-->
<!--        <template slot-scope="scope">-->
<!--          <span>{{ parseTime(scope.row.updatedTime, '{y}-{m}-{d} {h}:{i}') }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="申请人ID" align="center" prop="userId" />-->
<!--      <el-table-column label="申请人部门ID" align="center" prop="deptId" />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180" fixed="right">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.status === 'pending'"
            size="mini"
            type="text"
            icon="el-icon-s-promotion"
            @click="handleSubmit(scope.row)"
            v-hasPermi="['oa:overtime:submit']"
          >
            发送
          </el-button>
          <el-button
              size="mini"
              type="text"
              icon="el-icon-info"
              @click="handleInfo(scope.row)"
              v-hasPermi="['oa:overtime_apply:query']"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['oa:overtime_apply:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['oa:overtime_apply:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
      </template>
    </div>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改加班申请对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="68%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="24">
                <el-form-item label="加班事由" prop="reason">
                  <el-input v-model="form.reason" type="textarea" placeholder="请输入内容" />
                </el-form-item>
          </el-col>
          <el-col :span="8">
                <el-form-item label="开始时间" prop="startTime">
                  <el-date-picker filterable clearable
                    v-model="form.startTime"
                    type="datetime"
                    value-format="yyyy-MM-dd HH:mm"
                    placeholder="请选择开始时间">
                  </el-date-picker>
                </el-form-item>
          </el-col>
          <el-col :span="8">
                <el-form-item label="结束时间" prop="endTime">
                  <el-date-picker filterable clearable
                    v-model="form.endTime"
                    type="datetime"
                    value-format="yyyy-MM-dd HH:mm"
                    placeholder="请选择结束时间">
                  </el-date-picker>
                </el-form-item>
          </el-col>
      <el-col :span="8">
            <el-form-item label="加班时长" prop="duration">
              <el-input v-model="form.duration"  placeholder="系统已自动计算，可手动调整" />
            </el-form-item>
      </el-col>
          <el-col :span="24">
            <el-form-item label="审批人" prop="approverIds">
              <el-select
                v-model="form.approverIds"
                multiple
                filterable
                placeholder="请选择审批人"
                style="width: 100%"
              >
                <el-option
                  v-for="item in allEmpList"
                  :key="item.empId"
                  :label="item.empName"
                  :value="item.empId + ''"
                />
              </el-select>
            </el-form-item>
          </el-col>
<!--          <el-col :span="24">-->
<!--                <el-form-item label="审批人姓名" prop="approverNames">-->
<!--                  <el-input v-model="form.approverNames" type="textarea" placeholder="请输入内容" />-->
<!--                </el-form-item>-->
<!--          </el-col>-->
          <el-col :span="24">
            <el-form-item label="抄送人" prop="ccIds">
              <el-select
                v-model="form.ccIds"
                multiple
                filterable
                placeholder="请选择抄送人"
                style="width: 100%"
              >
                <el-option
                  v-for="item in allEmpList"
                  :key="item.empId"
                  :label="item.empName"
                  :value="item.empId + ''"
                />
              </el-select>
            </el-form-item>
          </el-col>
<!--          <el-col :span="24">-->
<!--                <el-form-item label="抄送人姓名" prop="ccNames">-->
<!--                  <el-input v-model="form.ccNames" type="textarea" placeholder="请输入内容" />-->
<!--                </el-form-item>-->
<!--          </el-col>-->
        <el-col :span="8" v-if="isAdmin">
                <el-form-item label="状态" prop="status">
                  <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%;">
                    <el-option
                      v-for="dict in dict.type.oa_overtime_apply_status"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
        </el-col>
          <el-col :span="8">
                <el-form-item label="申请时间" prop="applyTime">
                  <el-date-picker filterable clearable
                    v-model="form.applyTime"
                    type="datetime"
                    value-format="yyyy-MM-dd HH:mm"
                    placeholder="请选择申请时间">
                  </el-date-picker>
                </el-form-item>
          </el-col>
<!--          <el-col :span="8">-->
<!--                <el-form-item label="创建时间" prop="createdTime">-->
<!--                  <el-date-picker filterable clearable-->
<!--                    v-model="form.createdTime"-->
<!--                    type="datetime"-->
<!--                    value-format="yyyy-MM-dd"-->
<!--                    placeholder="请选择创建时间">-->
<!--                  </el-date-picker>-->
<!--                </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="8">-->
<!--                <el-form-item label="更新时间" prop="updatedTime">-->
<!--                  <el-date-picker filterable clearable-->
<!--                    v-model="form.updatedTime"-->
<!--                    type="datetime"-->
<!--                    value-format="yyyy-MM-dd"-->
<!--                    placeholder="请选择更新时间">-->
<!--                  </el-date-picker>-->
<!--                </el-form-item>-->
<!--          </el-col>-->
<!--      <el-col :span="8">-->
<!--            <el-form-item label="申请人ID" prop="userId">-->
<!--              <el-input v-model="form.userId"  placeholder="请输入申请人ID" />-->
<!--            </el-form-item>-->
<!--      </el-col>-->
<!--      <el-col :span="8">-->
<!--            <el-form-item label="申请人部门ID" prop="deptId">-->
<!--              <el-input v-model="form.deptId"  placeholder="请输入申请人部门ID" />-->
<!--            </el-form-item>-->
<!--      </el-col>-->
<!--      <el-col :span="8">-->
<!--            <el-form-item label="删除标记：0-正常，1-删除" prop="delFlag">-->
<!--              <el-input v-model="form.delFlag"  placeholder="请输入删除标记：0-正常，1-删除" />-->
<!--            </el-form-item>-->
<!--      </el-col>-->
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">保 存</el-button>
        <el-button type="success" @click="submitAndSend">提交并发送</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 加班申请详情对话框 -->
    <el-dialog :title="title" :visible.sync="openInfo" width="68%" append-to-body>
      <el-descriptions border >
                        <el-descriptions-item label="加班事由" >{{form.reason}}</el-descriptions-item>
                        <el-descriptions-item label="开始时间" >
                            {{ parseTime(form.startTime, '{y}-{m}-{d} {h}:{i}')}}
                        </el-descriptions-item>
                        <el-descriptions-item label="结束时间" >
                            {{ parseTime(form.endTime, '{y}-{m}-{d} {h}:{i}')}}
                        </el-descriptions-item>
                        <el-descriptions-item label="加班时长" >{{form.duration}}</el-descriptions-item>
<!--                        <el-descriptions-item label="审批人ID" >{{form.approverIds}}</el-descriptions-item>-->
                        <el-descriptions-item label="审批人姓名" >{{form.approverNames}}</el-descriptions-item>
<!--                        <el-descriptions-item label="抄送人ID" >{{form.ccIds}}</el-descriptions-item>-->
                        <el-descriptions-item label="抄送人姓名" >{{form.ccNames}}</el-descriptions-item>
                        <el-descriptions-item label="状态" >
                          <dict-tag :options="dict.type.oa_overtime_apply_status" :value="form.status"/>
                        </el-descriptions-item>
                        <el-descriptions-item label="申请时间" >
                            {{ parseTime(form.applyTime, '{y}-{m}-{d} {h}:{i}')}}
                        </el-descriptions-item>
<!--                        <el-descriptions-item label="创建时间" >-->
<!--                            {{ parseTime(form.createdTime, '{y}-{m}-{d} {h}:{i}')}}-->
<!--                        </el-descriptions-item>-->
<!--                        <el-descriptions-item label="更新时间" >-->
<!--                            {{ parseTime(form.updatedTime, '{y}-{m}-{d} {h}:{i}')}}-->
<!--                        </el-descriptions-item>-->
<!--                        <el-descriptions-item label="申请人ID" >{{form.userId}}</el-descriptions-item>-->
<!--                        <el-descriptions-item label="申请人部门ID" >{{form.deptId}}</el-descriptions-item>-->
<!--                        <el-descriptions-item label="删除标记：0-正常，1-删除" >{{form.delFlag}}</el-descriptions-item>-->
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listOvertime_apply, getOvertime_apply, delOvertime_apply, addOvertime_apply, updateOvertime_apply, listApproval, listCopied, sendEmail } from "@/api/oa/overtime_apply";
import { listUser } from "@/api/system/user";

export default {
  name: "Overtime_apply",
  dicts: ['oa_overtime_apply_status'],
  data() {
    return {
      activeTab: 'myApply',
      // 是否显示更多
      isShowMore: false,
      // el-table 高度
      loading: false,
      tableHeight: window.innerHeight - 200,
      // 普通用户各 Tab 数据
      myApplyList: [],
      approvalList: [],
      copiedList: [],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 加班申请表格数据（管理员）
      overtime_applyList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示详情弹出层
      openInfo: false,
      daterangeApplyTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        reason: null,
        startTime: null,
        endTime: null,
        duration: null,
        approverIds: null,
        approverNames: null,
        ccIds: null,
        ccNames: null,
        status: null,
        applyTime: null,
        createdTime: null,
        updatedTime: null,
        userId: null,
        deptId: null,
        params: {}
      },
      currentUserEmpName: this.$store.getters.nickName, // 获取当前登录用户名
      isAdmin: this.$store.getters.roles?.includes('admin') || false,
      // 表单参数
      form: {},
      allEmpList: [],
      empList: [],
      empMap: {},
      empLoading: false,
      // 表单校验
      rules: {
        reason: [
          { required: true, message: "加班事由不能为空", trigger: "blur" }
        ],
        startTime: [
          { required: true, message: "开始时间不能为空", trigger: "blur" }
        ],
        endTime: [
          { required: true, message: "结束时间不能为空", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              const start = this.form.startTime;
              if (start && value) {
                if (new Date(value) <= new Date(start)) {
                  callback(new Error("结束时间必须大于开始时间"));
                } else {
                  callback();
                }
              } else {
                callback();
              }
            },
            trigger: "blur"
          }
        ],
        duration: [
          { required: true, message: "加班时长不能为空", trigger: "blur" }
        ],
        approverIds: [
          { required: true, message: "审批人ID列表，英文逗号分隔不能为空", trigger: "blur" }
        ],
        approverNames: [
          { required: true, message: "审批人姓名列表，对应ID顺序不能为空", trigger: "blur" }
        ],
      }
    };
  },
  watch: {
    'form.startTime': function(newVal) {
      this.autoCalculateDuration();
    },
    'form.endTime': function(newVal) {
      this.autoCalculateDuration();
    }
  },
  computed: {
    // 假设通过 store 获取用户角色
    userRole() {
      return this.$store.getters.role || 'common';
    },
    isAdmin() {
      return this.userRole === 'admin';
    },
    currentUserId() {
      return this.$store.getters.userId;
    }
  },
  created() {
    this.loadAllEmployees();
    this.getList();
    this.setTableHeight();
    window.addEventListener('resize', this.setTableHeight); // 监听窗口大小变化
    if (this.isAdmin) {
      this.loadAllApplications(); // 管理员加载全部数据
    } else {
      this.loadMyApplyList(); // 普通用户默认加载我的加班
    }
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.setTableHeight); // 移除事件监听
  },
  methods: {
    loadAllEmployees() {
      listUser({}).then(res => {
        const users = res.rows || [];
        this.allEmpList = users.map(user => ({
          empId: user.userId,
          empName: user.nickName
        }));
        // 构建映射（用于显示姓名）
        users.forEach(user => {
          this.$set(this.empMap, user.userId, user.nickName);
        });
      }).catch(() => {
        this.$message.warning('加载员工列表失败');
      });
    },
    // 计算两个时间之间的加班时长（排除 8:30-12:00 和 13:30-18:00）
    calculateOvertimeDuration(startStr, endStr) {
      if (!startStr || !endStr) return null;

      const start = new Date(startStr);
      const end = new Date(endStr);

      if (end <= start) {
        this.$message.warning("结束时间必须大于开始时间");
        return null;
      }

      // 总分钟数
      const totalMinutes = (end - start) / (1000 * 60);

      // 计算正常工作时间内的分钟数
      let workMinutes = 0;
      let current = new Date(start);

      // 按天遍历
      while (current < end) {
        const dayEnd = new Date(current);
        dayEnd.setHours(23, 59, 59, 999);
        const segmentEnd = end < dayEnd ? end : dayEnd;

        // 当天的正常工作时间段（分钟）
        const workSegments = [
          { start: 8 * 60 + 30, end: 12 * 60 },       // 8:30 - 12:00
          { start: 13 * 60 + 30, end: 18 * 60 }       // 13:30 - 18:00
        ];

        for (const seg of workSegments) {
          const segStart = new Date(current);
          segStart.setHours(Math.floor(seg.start / 60), seg.start % 60, 0, 0);

          const segEnd = new Date(current);
          segEnd.setHours(Math.floor(seg.end / 60), seg.end % 60, 0, 0);

          // 计算与 [start, end] 的交集
          const overlapStart = segStart < start ? start : segStart;
          const overlapEnd = segEnd > end ? end : segEnd;

          if (overlapEnd > overlapStart) {
            workMinutes += (overlapEnd - overlapStart) / (1000 * 60);
          }
        }

        // 跳到下一天
        current.setDate(current.getDate() + 1);
        current.setHours(0, 0, 0, 0);
      }

      const overtimeMinutes = totalMinutes - workMinutes;
      const overtimeHours = Math.max(0, overtimeMinutes / 60);
      return parseFloat(overtimeHours.toFixed(2));
    },
    autoCalculateDuration() {
      const duration = this.calculateOvertimeDuration(this.form.startTime, this.form.endTime);
      if (duration !== null) {
        this.$set(this.form, 'duration', duration);
      }
    },
    /** 提交申请（发送邮件给审批人和抄送人） */
    handleSubmit(row) {
      this.$confirm('确定要提交该加班申请吗？系统将自动发送邮件通知审批人与抄送人。', '提示', {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        // 构造请求参数
        const params = {
          id: row.id,
          approverIds:row.approverIds,
          ccIds: row.ccIds,
          startTime: row.startTime,
          endTime: row.endTime,
          duration: row.duration,
          reason: row.reason,
          applicantName: this.$store.getters.nickName // 当前登录用户姓名
        };
        console.log('即将发送的参数:', params);
        console.log('approverIds 类型:', typeof params.approverIds); // 应该是 "string"
        console.log('approverIds 值:', params.approverIds);         // 应该是 "14" 或 "14,15"

        // 调用发送邮件接口
        this.loading = true;
        sendEmail(params)
          .then(res => {
            if (res && res.code === 200) {
              this.$message.success(res.msg || '提交成功');
            } else {
              this.$message.error(res?.msg || '提交失败');
            }
          })
          .catch(err => {
            console.error('邮件发送失败:', err);
            this.$message.error('网络错误，邮件发送失败！');
          })
          .finally(() => {
            this.loading = false;
          });
      }).catch(() => {
        this.$message.info('已取消提交');
      });
    },
    // 远程搜索员工
    searchEmps(query) {
      if (!query || query.trim() === '') {
        this.empList = [];
        return;
      }
      this.empLoading = true;

      // 查询用户列表（包含 userId 和 nickName）
      listUser({ keyword: query.trim() }) // 根据实际情况调整参数名
        .then(res => {
          const users = res.rows || [];
          this.empList = users.map(user => ({
            empId: user.userId,   // 为了兼容原代码，临时映射
            empName: user.nickName
          }));
          // 构建 userId -> nickName 映射
          users.forEach(user => {
            this.$set(this.empMap, user.userId, user.nickName);
          });
          this.empLoading = false;
        })
        .catch(() => {
          this.$message.error('搜索用户失败');
          this.empList = [];
          this.empLoading = false;
        });
    },
    submitAndSend() {
      this.$refs["form"].validate(valid => {
        if (!valid) return;

        const approverIds = this.form.approverIds;
        const ccIds = this.form.ccIds;

        if (!approverIds || approverIds.length === 0) {
          this.$message.warning("请至少选择一位审批人");
          return;
        }

        const approverNames = approverIds.map(id => this.empMap[id]).filter(name => name).join('、');
        const ccNames = ccIds.map(id => this.empMap[id]).filter(name => name).join('、');

        const submitData = { ...this.form };
        submitData.approverIds = approverIds.join(',');
        submitData.ccIds = ccIds.join(',');
        submitData.approverNames = approverNames;
        submitData.ccNames = ccNames;

        // 如果是新增，则设置状态为“待审批”
        if (!this.form.applyId) {
          submitData.status = 'pending'; // 新增时自动设为待审批
        }

        const request = this.form.id ? updateOvertime_apply(submitData) : addOvertime_apply(submitData);
        this.loading = true;
        request.then(res => {
          if (res.code === 200) {
            this.$message.success("保存成功，正在发送邮件...");
            const emailParams = {
              id: res.data?.id || this.form.id,
              applicantName: this.currentUserEmpName,
              approverIds: submitData.approverIds,
              ccIds: submitData.ccIds,
              startTime: submitData.startTime,
              endTime: submitData.endTime,
              duration: submitData.duration,
              reason: submitData.reason
            };
            return sendEmail(emailParams).then(emailRes => {
              if (emailRes.code === 200) {
                this.$message.success("邮件已发送");
              } else {
                this.$message.warning("邮件发送失败: " + (emailRes.msg || '未知错误'));
              }
            });
          }
        }).then(() => {
          this.open = false;
          this.getList();
        }).catch(err => {
          console.error("提交或邮件发送失败:", err);
          this.$message.error("操作失败，请重试");
        }).finally(() => {
          this.loading = false;
        });
      });
    },
    handleTabClick(tab) {
      if (tab.name === 'myApply' && this.myApplyList.length === 0) {
        this.loadMyApplyList();
      } else if (tab.name === 'approval' && this.approvalList.length === 0) {
        this.loadApprovalList();
      } else if (tab.name === 'copied' && this.copiedList.length === 0) {
        this.loadCopiedList();
      }
    },

    // 普通用户：我的加班记录（我自己提交的）
    loadMyApplyList() {
      this.loading = true;
      const params = {
        applicantId: this.currentUserId,
        ...this.queryParams // ✅ 合并查询条件（如 startTime, durationDays 等）
      };
      listOvertime_apply(params).then(res => {
        this.myApplyList = res.rows || [];
        this.total = res.total; // 用于分页组件
      }).catch(err => {
        this.$message.error('加载我的加班记录失败');
      }).finally(() => {
        this.loading = false;
      });
    },

    // 普通用户：我需要审批的
    loadApprovalList() {
      this.loading = true;
      // 后端支持查询：当前用户是审批人 的记录
      listApproval().then(res => {
        this.approvalList = res.rows || [];
      }).catch(err => {
        this.$message.error('加载审批记录失败');
      }).finally(() => {
        this.loading = false;
      });
    },

    // 普通用户：抄送给我的
    loadCopiedList() {
      this.loading = true;
      // 后端支持查询：当前用户在抄送人列表中
      listCopied().then(res => {
        this.copiedList = res.rows || [];
      }).catch(err => {
        this.$message.error('加载抄送记录失败');
      }).finally(() => {
        this.loading = false;
      });
    },

    // 管理员：加载所有加班记录（不加筛选条件）
    loadAllApplications() {
      this.loading = true;
      // 不传任何筛选条件 → 获取全部数据
      listOvertime_apply({}).then(res => {
        this.applyList = res.rows || [];
      }).catch(err => {
        this.$message.error('加载全部加班记录失败');
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 查询加班申请列表 */
    getList() {
      this.loading = true;
      // 构造请求参数
      const params = { ...this.queryParams };

      if (null != this.daterangeApplyTime && '' != this.daterangeApplyTime) {
        this.queryParams.params["beginApplyTime"] = this.daterangeApplyTime[0];
        this.queryParams.params["endApplyTime"] = this.daterangeApplyTime[1];
      }

      // 如果不是管理员，则只查询包含当前用户的记录（作为审批人或抄送人）
      if (!this.isAdmin) {
        params.includeMe = true; // 告诉后端：只返回当前用户是审批人或抄送人的记录
        params.currentUserName = this.currentUserEmpName; // 传当前用户名用于匹配
      }
      listOvertime_apply(this.queryParams).then(response => {
        this.overtime_applyList = response.rows;
        this.total = response.total;
        this.loading = false;
      }).catch(() => {
        this.$message.error('加载加班申请列表失败');
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openInfo = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        reason: null,
        startTime: null,
        endTime: null,
        duration: null,
        approverIds: null,
        approverNames: null,
        ccIds: null,
        ccNames: null,
        status: null,
        applyTime: null,
        createdTime: null,
        updatedTime: null,
        userId: null,
        deptId: null,
        createBy: null,
        updateBy: null,
        delFlag: null
      };
      this.resetForm("form");
      this.empList = []; // 清空缓存的员工列表
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      if (this.isAdmin) {
        this.getList();
      } else {
        this.loadMyApplyList(); // ✅ 普通用户调用正确的加载方法
      }
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeApplyTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.status = 'pending'; // 新增默认状态
      this.open = true;
      this.title = "添加加班申请";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getOvertime_apply(id).then(response => {
        const data = response.data;
        // 1. 先复制数据
        this.form = { ...data };

        // 2. 将字符串转为数组（注意：split后是字符串数组，要转成数字或保持字符串）
        this.form.approverIds = data.approverIds ? data.approverIds.split(',').map(id => id.trim()) : [];
        this.form.ccIds = data.ccIds ? data.ccIds.split(',').map(id => id.trim()) : [];

        // 3. 加载溢选人员部分
        const selectedUserIds = [
          ...this.form.approverIds,
          ...this.form.ccIds
        ].map(id => parseInt(id)).filter(id => !isNaN(id));

        if (selectedUserIds.length > 0) {
          this.empLoading = true;
          listUser({ userIds: selectedUserIds }) // 查询用户信息
            .then(res => {
              const userData = Array.isArray(res?.rows) ? res.rows : [];
              this.empList = userData.map(u => ({
                empId: u.userId,
                empName: u.nickName
              }));

              // 构建 userId -> nickName 映射
              userData.forEach(u => {
                if (u?.userId && u?.nickName) {
                  this.$set(this.empMap, u.userId, u.nickName);
                }
              });

              this.empLoading = false;
            })
            .catch(err => {
              console.error('加载已选用户失败:', err);
              this.$message.warning('未能加载审批人/抄送人姓名');
              this.empLoading = false;
            });
        } else {
          this.empList = [];
        }

        this.open = true;
        this.title = "修改加班申请";
      });
    },
    /** 详情按钮操作 */
    handleInfo(row) {
      this.reset();
      const id = row.id || this.ids
      getOvertime_apply(id).then(response => {
        this.form = response.data;
        this.openInfo = true;
        this.title = "加班申请详情";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) return;

        // ✅ 此时 form.approverIds 已经是 empId 数组了
        const approverIds = this.form.approverIds;
        const ccIds = this.form.ccIds;

        // ✅ 可选：根据 empId 获取姓名（用于显示）
        const approverNames = approverIds
          .map(id => this.empMap[id])
          .filter(name => name);

        if (approverIds.length > 0 && approverNames.length === 0) {
          this.$message.warning('所选审批人未在系统中找到对应姓名，请重新选择');
          return;
        }

        // ✅ 准备提交数据
        const submitData = { ...this.form };

        // 数据库字段兼容：ID 列表用逗号分隔
        submitData.approverIds = approverIds.join(',');
        submitData.ccIds = ccIds.join(',');

        // 姓名也保存（可选）
        submitData.approverNames = approverNames.join(',');
        submitData.ccNames = ccIds.map(id => this.empMap[id]).filter(name => name).join(',');

        // 提交
        if (this.form.id != null) {
          updateOvertime_apply(submitData).then(() => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
        } else {
          submitData.status = 'pending';
          addOvertime_apply(submitData).then(() => {
            this.$modal.msgSuccess("新增成功");
            this.open = false;
            this.getList();
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除加班申请编号为"' + ids + '"的数据项？').then(function() {
        return delOvertime_apply(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('oa/overtime_apply/export', {
        ...this.queryParams
      }, `加班申请数据导出_${new Date().getTime()}.xlsx`)
    },
    // 设置表格高度
    setTableHeight() {
      const appContainer = document.getElementById('app-container');
      if (appContainer) {
        this.tableHeight = appContainer.clientHeight * 0.8;
      }
    }
  },
  mounted() {
    // 动态设置高度
    this.tableHeight = window.innerHeight - 200;
    window.onresize = () => {
      this.tableHeight = window.innerHeight - 200;
    };
  },
};
</script>
<style scoped>
.apply-container {
  padding: 16px;
  background-color: #fff;
}
.el-table {
  margin-top: 10px;
}
</style>
